// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

// 云函数入口函数
exports.main = async (event, context) => {
  // 1.小程序调用云端才有, 其他情况调用没有openid直接报错
  const openid = cloud.getWXContext().OPENID
  if (!(openid && openid === event.openid)) {
    return {
      errCode: 401,
      errorMsg: '未登录，没有权限！'
    }
  }




  // 2.校验客户端数据
  const db = cloud.database()
  let errCheck
  let clientData = event.data
  // 新增openid,创建时间,更新时间
  let databaseData = {
    update_time: new Date().getTime(),
    nickName: clientData.nickName || '',
    avatarUrl: clientData.avatarUrl || '',
    bgImg: clientData.bgImg || '',
    classifyList: clientData.classifyList || [],
    foodsList: clientData.foodsList || [],
    menuDesc: clientData.menuDesc || '',
    menuName: clientData.menuName || '',
    menuTips: clientData.menuTips || '',
    stepsList: clientData.stepsList || []
  }
  if (!databaseData.bgImg) {
    errCheck = "请上传封面图！"
  }

  if (!databaseData.menuName) {
    errCheck = "请填写菜谱名称！"
  }

  if (!(databaseData.stepsList[0] && databaseData.stepsList[0].desc)) {
    errCheck = "至少填写一个步骤描述"
  }

  if (errCheck) {
    return {
      errorMsg: errCheck
    }
  }


  // 3. 设置查询语句
  let _id = event.data.id
  if (!_id) {
    return {
      errorMsg: '请上传菜谱id！'
    }
  }

  let conditionSQL = {
    _id,
    openid
  }


  // 4.开始使用数据库语句
  const [err, success] = await awaitWrap(
    db.collection('menus').where(conditionSQL).update({
      // data 字段表示需更新字段放入对象
      data: databaseData
    })
  )

  if (success) {
    if (success.stats.updated === 0) {
      return {
        errorMsg: '不存在的菜谱id，更新失败'
      }
    }

    if (success.stats.updated === 1) {
      return {
        msg: 'success'
      }
    }


  } else {
    return {
      errorMsg: err
    }
  }


}

// await错误处理公共方法
const awaitWrap = (promise) => {
  return promise
    .then(success => [null, success])
    .catch(err => [err, null])
}